import { Controller } from 'egg';

const openFlowRule = {
  schemaCode: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  flowId: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
};
const closeFlowRule = {
  schemaCode: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
};
const getFlowDefineRule = {
  flowId: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
};
const saveFlowRule = {
  flowId: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  flowName: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  description: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  defineData: {
    type: 'object',
    required: true,
    allowEmpty: false,
  },
};

export default class flow extends Controller {
  async openFlow() {
    const { ctx, service, logger } = this;
    const params = Object.assign({}, ctx.request.body);
    try {
      ctx.validate(openFlowRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const result = await service.flow.openFlow(params);
    ctx.body = ctx.response.success(result);
  }
  async closeFlow() {
    const { ctx, service, logger } = this;
    const params = Object.assign({}, ctx.request.body);
    try {
      ctx.validate(closeFlowRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const result = await service.flow.closeFlow(params);
    ctx.body = ctx.response.success(result);
  }
  async getFlowDefine() {
    const { ctx, service, logger } = this;
    const params = Object.assign({}, ctx.query, ctx.params);
    console.log('打印：params', params);
    try {
      ctx.validate(getFlowDefineRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const result = await service.flow.getFlowDefine(params);
    ctx.body = ctx.response.success(result);
  }
  async saveFlow() {
    const { ctx, service, logger } = this;
    const params = Object.assign({}, ctx.request.body);
    try {
      ctx.validate(saveFlowRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const result = await service.flow.saveFlow(params);
    ctx.body = ctx.response.success(result);
  }
}
